﻿using FB.Enums;
using FB.Mvc.Controllers;
using FB.Providers;
using FB.Providers.EmployeeInfo;
using FCDB.Entity;
using FCDB.Entity.BusiReportEntity;
using FCDB.Entity.EntityEx;
using FCDB.Repository;
using FCDB.Web.Models;
using FCDB.WEB.Models;
using FOA.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FCDB.WEB.Controllers
{
    [FB.Membership.Annotations.AuthorizeOnly]
    public class BusinessReportController : BaseController
    {
        private BusiReportRepository busiReportRepository = new BusiReportRepository();

        //**   业务明细
        public ActionResult BusinessDetail( BusinessReportModel model)
        {
            if (model.pageIndex == null)
                model.pageIndex = 1;
            if (model.pageSize == null)
                model.pageSize = 10;
            if (!model.dtStart.HasValue)
                model.dtStart = DateTime.Now.Date.AddMonths(-1);
            if (!model.dtEnd.HasValue)
                model.dtEnd = DateTime.Now.Date.AddDays(1);
            model.UserID = this.UserID;
            int total = 0;
            IList<ReportFieldSettings> reportFieldList = busiReportRepository.GetUserFieldSettingList(this.UserID); 
            IList<FormCDBEx> BusiDetailList = busiReportRepository.GetBusiDetail(model , out total);
            PagedList<FormCDBEx> list = new PagedList<FormCDBEx>(BusiDetailList, model.pageIndex.Value, model.pageSize.Value, total);
            FCDB.Entity.ReportFieldSettings defaultReportFieldSettings = null;
            if (reportFieldList.Count() > 0)
            {
                if (model.defaultFieldID.HasValue)
                {
                    defaultReportFieldSettings = reportFieldList.First(t => t.ID == model.defaultFieldID.Value);
                }
                else
                {
                    defaultReportFieldSettings = reportFieldList.OrderByDescending(t => t.UpdateTime).FirstOrDefault(t => t.IsDefault == true);
                    if (defaultReportFieldSettings == null)
                    {
                        defaultReportFieldSettings = reportFieldList.OrderByDescending(t => t.UpdateTime).First();
                    }
                }
                String strFieldContent = defaultReportFieldSettings.FieldContent;
            }
            IList<String> fieldList = new List<String>();
            if (defaultReportFieldSettings != null && !String.IsNullOrEmpty(defaultReportFieldSettings.FieldContent))
            {
                String[] fields = defaultReportFieldSettings.FieldContent.Split(",".ToArray());
                foreach (String item in fields)
                {
                    if (!String.IsNullOrEmpty(item.Trim()))
                    {
                        fieldList.Add(item);
                    }
                }
            }
            ViewBag.DefaultReportFieldSettings = defaultReportFieldSettings;
            ViewBag.FieldList = fieldList;
            ViewBag.ReportFieldList = reportFieldList;
            ViewBag.BusiModel = model;
            return View(list);
        }

        public ActionResult BusinessDeductDetailReport(BusinessReportModel model)
        {
            if (model.pageIndex == null)
                model.pageIndex = 1;
            if (model.pageSize == null)
                model.pageSize = 10;
            if (!model.dtStart.HasValue)
                model.dtStart = DateTime.Now.Date.AddMonths(-1);
            if (!model.dtEnd.HasValue)
                model.dtEnd = DateTime.Now.Date.AddDays(1);
            model.UserID = this.UserID;
            int total = 0;
            IList<FormCDBEx> BusiDetailList = busiReportRepository.GetBusiDetail(model, out total);
            PagedList<FormCDBEx> list = new PagedList<FormCDBEx>(BusiDetailList, model.pageIndex.Value, model.pageSize.Value, total);
            ViewBag.BusiModel = model;
            return View(list);

        }
        public ActionResult BusinessDeductReport(BusinessReportModel model)
        {
            if (model.pageIndex == null)
                model.pageIndex = 1;
            if (model.pageSize == null)
                model.pageSize = 10;
            if (!model.dtStart.HasValue)
                model.dtStart = DateTime.Now.Date.AddMonths(-1);
            if (!model.dtEnd.HasValue)
                model.dtEnd = DateTime.Now.Date.AddDays(1);
            model.UserID = this.UserID;
            int total = 0;
            IList<BusinessDeductReportModel> BusiDetailList = busiReportRepository.getBusinessDeductReport(model, out total);
            PagedList<BusinessDeductReportModel> list = new PagedList<BusinessDeductReportModel>(BusiDetailList, model.pageIndex.Value, model.pageSize.Value, total);
            ViewBag.BusiModel = model;
            return View(list);
            
        }
       
         

        public ActionResult UserFieldSetting(String id)
        {
            ReportFieldSettings fieldSetting = new ReportFieldSettings();
            if (!String.IsNullOrEmpty(id))
            {
                fieldSetting = busiReportRepository.Get<ReportFieldSettings>(long.Parse(id));
            }
            return PartialView(fieldSetting);
        }


        public ActionResult FeildSetting()
        {
            IList<ReportFieldSettings> list = busiReportRepository.GetUserFieldSettingList(this.UserID);
            return View(list);
        }
        public ActionResult SaveFeildSetting(String id, String name, bool isDefault, String strFields)
        {
            IList<ReportFieldSettings> list = busiReportRepository.GetUserFieldSettingList(this.UserID);
            RtnMsg rtnMsg = new RtnMsg();
            if (String.IsNullOrEmpty(id) || id == "0")
            {
                //保存
                ReportFieldSettings fieldSetting = new ReportFieldSettings()
               {
                   IsEnable = true,
                   Name = name,
                   CreateTime = DateTime.Now,
                   UpdateTime = DateTime.Now,
                   UserID = this.UserID,
                   FieldContent = strFields,
                   IsDefault = isDefault,
                   ID = IDCreateLogic.GenerateID("ReportFieldSettings", "用户业务字段数据")
               };
                if (isDefault == true)
                {
                    foreach (ReportFieldSettings item in list)
                    {
                        item.IsDefault = false;
                        busiReportRepository.Update(item);
                        busiReportRepository.SaveChagnes();
                    }
                }
                busiReportRepository.Add(fieldSetting);
                busiReportRepository.SaveChagnes();
            }
            else
            {
                long fieldSettingID = long.Parse(id);
                //修改
                ReportFieldSettings fieldSetting = LogicBase.DBHelper.ReportFieldSettings.FirstOrDefault(t => t.ID == fieldSettingID);
                fieldSetting.Name = name;
                fieldSetting.UpdateTime = DateTime.Now;
                fieldSetting.IsDefault = isDefault;
                fieldSetting.FieldContent = strFields;
                busiReportRepository.Update(fieldSetting);
                busiReportRepository.SaveChagnes();
            }
            JsonResult jsonResult = new JsonResult()
           {
               JsonRequestBehavior = JsonRequestBehavior.AllowGet,
               Data = "ok"
           };
            return jsonResult;
        }

        public ActionResult DeleteFeildSetting(String id)
        {
            long lid = long.Parse(id);
            ReportFieldSettings fieldSettings = busiReportRepository.Get<ReportFieldSettings>(lid);
            if (fieldSettings != null)
            {
                fieldSettings.IsEnable = false;
                busiReportRepository.Update(fieldSettings);
                busiReportRepository.SaveChagnes();
            }
            JsonResult jsonResult = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = "ok"
            };
            return jsonResult;
        }
        public ActionResult PermissionsSettings(String UserID)
        {
            return View(); 

        }
        public ActionResult SavePermissionsSettings(String userID, String DeptCode, String DeptName)
        {
            JsonResult jsonResult = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = "ok"
            };
            if (String.IsNullOrEmpty(userID) || String.IsNullOrEmpty(DeptCode) || String.IsNullOrEmpty(DeptName))
                return jsonResult;
            Guid gUserID = Guid.Parse(userID);
            IList<UserBusinessPermissions> list = LogicBase.DBHelper.UserBusinessPermissions.Where(t => t.UserID == gUserID).ToList();
            if (list.FirstOrDefault(t => t.DEPTCode == DeptCode) != null)
                return jsonResult;
            UserBusinessPermissions ubp = new UserBusinessPermissions()
            {
                ID = IDCreateLogic.GenerateID("UserBusinessPermissions", "用户业务权限数据"),
                DEPTCode = DeptCode,
                DeptName = DeptName,
                UserID = gUserID
            };
            busiReportRepository.Add(ubp);
            busiReportRepository.SaveChagnes();
            return jsonResult;
        }
        public ActionResult UCPermissionsSettings(String userID)
        {
            if (String.IsNullOrEmpty(userID))
            {
                IList<UserBusinessPermissions> list = new List<UserBusinessPermissions>();
                return PartialView("UCPermissionsSettings", list);
            }
            else
            {
                Guid gUserID = Guid.Parse(userID);
                IList<UserBusinessPermissions> list = LogicBase.DBHelper.UserBusinessPermissions.Where(t => t.UserID == gUserID).ToList();
                return PartialView("UCPermissionsSettings", list);
            }

        }

        public ActionResult DeletePermissionsSettings(String id)
        {
            long lid = long.Parse(id);
            UserBusinessPermissions fieldSettings = busiReportRepository.Get<UserBusinessPermissions>(lid);
            if (fieldSettings != null)
            {
                busiReportRepository.Delete<UserBusinessPermissions>(lid);
                busiReportRepository.SaveChagnes();
            }
            JsonResult jsonResult = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = "ok"
            };
            return jsonResult;
        }

        public void SaveFile(string strContent, string FileName)
        {
            if (strContent != null && FileName != null)
            {
                TempData["strContent"] = null;
                TempData["FileName"] = null;
                TempData["strContent"] = strContent;
                TempData["FileName"] = FileName;
            }
            else
            {
                strContent = TempData["strContent"].ToString();
                FileName = TempData["FileName"].ToString();
                TempData["strContent"] = null;
                TempData["FileName"] = null;
                strContent = Server.UrlDecode(strContent);  // 进行解密
                FileName = FileName + DateTime.Now.ToString("yyyyMMddmmsstt");
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "GB2312";
                Response.ContentType = "application/ms-excel";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                //this.Page.EnableViewState = false;  
                // 添加头信息，为"文件下载/另存为"对话框指定默认文件名  
                Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
                // 把文件流发送到客户端  
                Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
                Response.Write(strContent);
                Response.Write("</body></html>");
                // 停止页面的执行  
                Response.End();
            }

        }

    }
}
